package com.hcb.tonguetiphealth.widget.bookOnline;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.model.ResDish;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.BottomWidget;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class DishOrderMsgOkWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "DishOrderMsgOkWidget";
	
	private Activity ctx;
	private Handler mHandler;
	private Button  btOk;
	private EditText etName, etTel, etInfo;
	private TextView tvTotalNum, tvTotalPrice;
	private DatePicker datePicker;
	private boolean isSucceed = false;
	private String resId, cityId, userId;
	private String dishId = "", dishNum = "", totalNum, totalPrice, time, linkman ,tel,info;
	private LinearLayout llback;
	private int year ,monthOfYear , dayOfMonth;
	
	public DishOrderMsgOkWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.dish_order_ok, this); 
		new BottomWidget(ctx, this);
		resId = ctx.getIntent().getStringExtra("resId");
		if (Global.DEBUG) {
			System.out.println("resId:"+resId);
		}
		bindView();
		bindEvent();
		initData();
	}
	
	private  void bindView(){
		 
		tvTotalNum = (TextView)findViewById(R.id.dish_order_dish_num_textview);
		tvTotalPrice = (TextView)findViewById(R.id.dish_order_total_price_textview);
		
		datePicker = (DatePicker)findViewById(R.id.dish_order_datePicker);
		
		etName = (EditText)findViewById(R.id.dish_order_contact_person_edittext);
		etTel = (EditText)findViewById(R.id.dish_order_tel_edittext);
		etInfo = (EditText)findViewById(R.id.dish_order_info_edittext);
		
		llback = (LinearLayout)findViewById(R.id.dish_order_linearlayout_back);
		
		btOk  =(Button)findViewById(R.id.dish_order_info_ok_button); 
	}
	
	private void bindEvent(){
		llback.setOnClickListener(this);
		btOk.setOnClickListener(this);
		
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在提交订单...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					if(isSucceed) {
						showMessage(ctx, "预订成功");
					} else {
						showMessage(ctx, "预订失败");
					}
					btOk.setClickable(true);
					dismissMessageDialog();
					new Thread(){
						public void run(){
							try {
								Thread.sleep(3000);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}.start();
					ctx.finish();
					break;
				case MessageWhat.NETWORK_FAILD:
					try {
					  dismissMessageDialog();
					} catch (Exception e) {
						// TODO: handle exception
					}
					//Toast.makeText(ctx,  "网络有点不给力哦", Toast.LENGTH_LONG).show();
					showMessage(ctx, R.string.net_faild);
					break;
				}
			}
		};
	}
	
	public void onClick(View v) {
		switch(v.getId()) {
		 
		case R.id.dish_order_info_ok_button:
			if(isSucceed) {
				showMessage(ctx, "此订单已购买成功");
			} else {
				checkMsg();
			}
			break;
		case R.id.dish_order_linearlayout_back:
			 ctx.setContentView(new DishOrderWidget(ctx));
			break;
		default:
			break;
		}
	}
	
	private void checkMsg() {
		linkman = etName.getText().toString();
		tel = etTel.getText().toString();
		info = etInfo.getText().toString();
		if (linkman != null && linkman.equals("")) {
			showMessage(ctx, "联系人不能为空！");
			return;
		}
		if (tel != null && tel.equals("")) {
			showMessage(ctx, "联系号码不能为空！");
			return;
		}
		SharedPreferences preferences = ctx.getSharedPreferences(Global.CITYID,
				0);
		cityId = preferences.getString(Global.CITYID, Global.defaultCityId);
		if (Global.user == null ) {
			login();
		}else {
			userId = Global.user.getUserId();
			commitOrder();
		}
	}
	
	private void commitOrder(){
		
		btOk.setClickable(false);
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);		
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				params.add(new BasicNameValuePair("areaId", cityId));
				params.add(new BasicNameValuePair("resId", resId));
				params.add(new BasicNameValuePair("userid", userId));
				params.add(new BasicNameValuePair("dishId", dishId));
				params.add(new BasicNameValuePair("dishNum", dishNum));
				params.add(new BasicNameValuePair("totalNum", totalNum));
				params.add(new BasicNameValuePair("totalPrice", totalPrice));
				params.add(new BasicNameValuePair("time", time));
				params.add(new BasicNameValuePair("linkman", linkman));
				params.add(new BasicNameValuePair("tel", tel));
				params.add(new BasicNameValuePair("info", info));
				String respone = HttpUtils.Post1(Global.getServletDishOrder(), params);
				if (respone!=null) {
					try {
						System.out.println("respone:"+respone);
						JSONObject jsonObject = new JSONObject(respone);
						String strReturn = jsonObject.getString("return");
						if ("true".equals(strReturn)) {
							isSucceed = true;
						}else {
							isSucceed = false;
						}
						String strMsg = jsonObject.getString("msg");
						if (Global.DEBUG) {
							System.out.println("msg:"+strMsg);
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						isSucceed = false;
						e.printStackTrace();
					}
					mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);		
				}else {
					isSucceed = false;
					mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);		
				}
			}
		}.start();
		
	}
	
	private void initData(){
		
		Calendar calendar = Calendar.getInstance();
		year = calendar.get(Calendar.YEAR);
		monthOfYear = calendar.get(Calendar.MONTH);
		dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
		time = year + monthOfYear + dayOfMonth + "";
		 
		datePicker.init(year, monthOfYear, dayOfMonth,
				new OnDateChangedListener() {

					public void onDateChanged(DatePicker view, int sltYear,
							int sltMonthOfYear, int sltDayOfMonth) {
						year = sltYear;
						monthOfYear = sltMonthOfYear;
						dayOfMonth = sltDayOfMonth; 
						time = year + monthOfYear + dayOfMonth + "";
					}

				});
		float fTotalPrice = 0;
		int iTotalNum = 0;
		for (int i = 0; i < Global.resDishOrderList.size(); i++) {
			ResDish tempDish = Global.resDishOrderList.get(i);
			fTotalPrice += StringUtils.parseFloat(tempDish.getPrice()) * StringUtils.parseInt(tempDish.getOrderNum());
			iTotalNum += StringUtils.parseInt(tempDish.getOrderNum());
			dishId += tempDish.getId() + ",";
			dishNum += tempDish.getOrderNum() + ",";
		}
		System.out.println("dishId:"+dishId);
		System.out.println("dishNum:"+dishNum);
		dishId = dishId.substring(0,dishId.lastIndexOf(","));
		dishNum = dishNum.substring(0, dishNum.lastIndexOf(","));
		totalPrice = fTotalPrice + "";
		totalNum = iTotalNum + "";
		tvTotalPrice.setText(fTotalPrice + "");
		tvTotalNum.setText(iTotalNum + "");
	}
 
	@Override
	public void notifyAdapter() {
		
	}
}
